from ferris import BasicModel
from google.appengine.ext import ndb
from app.models import util
from app.models.feature import Feature


class Artist(BasicModel):
    """
    Models the names of artists appearing in features.
    """
    name = ndb.StringProperty(required=True)
    name_sort = ndb.ComputedProperty(lambda self:
                                     util.homogenize_name(self.name))
    search_terms = ndb.ComputedProperty(lambda self:
                                        util.create_search_terms(self.name),
                                        repeated=True)

    @classmethod
    def list_query(cls, query=None):
        """
        List all artists with an optional query string, ordered alphabetically.
        """
        if query:
            search_args = util.prepare_search_args(query)
            results = cls.query(cls.search_terms.IN(search_args))
        else:
            results = cls.query()

        return results.order(cls.name_sort, cls.key)

    def all_features(self):
        """
        List all features where the artist appears.
        """
        return Feature.query(Feature.artist == self.key).order(
            -Feature.publication_day)

    def _post_put_hook(self, future):
        """
        Post put hook to force an update on each feature associated with this
        artist to make sure computed fields are kept up-to-date.
        """
        key = future.get_result()
        if key:
            query = Feature.query(Feature.artist == key)
            query.map(util.update_entity_async)
